package com.tanhua.server.service;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.RemainingTimes;
import com.tanhua.domain.vo.ErrorResult;
import com.tanhua.domain.vo.VoiceVo;
import com.tanhua.dubbo.api.RemainingTimesApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VoiceApi;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.Reference;
import org.bson.types.ObjectId;

import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.domain.mongo.Voice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Service
public class PeachblossomService {

    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    @Reference
    private VoiceApi voiceApi;


    /**
     * 接口名称：桃花传音-发送语音（学生实战） fastDFS
     * 接口路径：POST/peachblossom
     */
    public ResponseEntity<Object> uploadVoice(MultipartFile soundFile) throws IOException {
        //1.语音上传到fastDFS
        String voiceFileName = soundFile.getOriginalFilename();
        String ext = voiceFileName.substring(voiceFileName.lastIndexOf(".") + 1);//从.后一位截取到最后一位
        StorePath storePath = fastFileStorageClient.uploadFile(soundFile.getInputStream(), soundFile.getSize(), ext, null);
        String voiceUrl = fdfsWebServer.getWebServerUrl() + storePath.getFullPath();
        //2.创建实体类Voice把文件存到mongoDB数据库中
        //保存Voice
        Voice voice = new Voice();
//        voice.setId(new ObjectId()); 自增长
        voice.setUserId(UserHolder.getUserId());
        voice.setVoiceUrl(voiceUrl);
        voice.setCreated(System.currentTimeMillis());

        voiceApi.save(voice);

        return ResponseEntity.ok(null);
    }
    @Reference
    private RemainingTimesApi remainingTimesApi;

    @Reference
    private UserInfoApi userInfoApi;

    /**
     * 接口名称：桃花传音-接收语音（学生实战） 随机返回一个语音 喜欢-探花-喜欢
     * 接口路径：GET/peachblossom
     */
    public ResponseEntity<Object> recieveVoice() {
        //点击接收语音 返回前端需要的信息
        //1.调用服务api随机查询出一条语音 类调用方法，要使用静态方法
        //自己的语音不接收
        Voice voice = (Voice) voiceApi.queryVoice(UserHolder.getUserId());

        if (voice == null) {
            return ResponseEntity.status(400).body(ErrorResult.notVoice());
        }

        //2.创建并封装实体类VoiceVo
        VoiceVo voiceVo = new VoiceVo();
        voiceVo.setId(voice.getUserId());

        UserInfo userInfo = userInfoApi.findById(voice.getUserId());
        if (userInfo == null) {
            return ResponseEntity.status(404).body(null);
        }
        voiceVo.setAvatar(userInfo.getAvatar());
        voiceVo.setNickname(userInfo.getNickname());
        voiceVo.setAge(userInfo.getAge());
        voiceVo.setGender(userInfo.getGender());
        voiceVo.setSoundUrl(voice.getVoiceUrl());

        //总共10次，如果是当前用户就少一次 查出当前用户的就收语音的剩余次数 一开始每个用户默认10次
        Long remainingTimes = remainingTimesApi.count(UserHolder.getUserId());
        remainingTimes--;

        if (remainingTimes < 0) {
            remainingTimes = 0l;
            //就不能返回数据了
            return ResponseEntity.status(404).body(ErrorResult.notRemaining());
        }

        //要重新设置修改voice表中的剩余次数的值
        remainingTimesApi.modifyTimes(remainingTimes.intValue(),UserHolder.getUserId());



        voiceVo.setRemainingTimes(remainingTimes.intValue());

        //3.查询一条语音并且复制给voiceVo后，删除语音voice
        voiceApi.delete(voice);

        //4.返回结果
        return ResponseEntity.ok(voiceVo); //返回一个voicevo
    }
}
